var audioplayUtil = require("../../../utils/audioplay.js")
var share = require("../../../utils/share.js")
var app = getApp();
var id = ""; //获取分类id 
var startPoint = 1; //起始数据标记
var dataParm = {}; //封装请求数据
var page; //分页操作数据
var shareTickets = "";
var dislikeindex = 0;
Page({
  data: {
    alldata: [],
    lookmore: true,
    allfamilysearchhistory:[],
    openfamilysearch:true,
    lookmorehistory: true,
    allhistorydata: [],
    authbg: getApp().globalData.source + "red_packet/bg.png",
    authtitle: getApp().globalData.source + "red_packet/title1.png",
    authbtn2: getApp().globalData.source + "red_packet/btn2.png",
    authdialog: getApp().globalData.source + "dialog/dialog.png",
    content: '',
    classfilyDataListProgram: [],
    recomendListProgram: [],
    indexNumberProgram: null, //当前播放音频下标
    before: true,
    classfilyDataList: [],
    indexNumber: null, //当前播放音频下标

    timer: '', //播放时间 播放时间统计
    currentPosition: 0, //选定音频的播放位置
    duration: 0, //选定音频的长度
    free: true,
    play: true,
    url: ""
  },
  bindGetUserInfo: function(e) {
    getApp().authInfo(e);
  },
  commitformid: function(e) {
    var that = this;
    //获取推送消息fromID
    let formId = e.detail.formId;
    // console.log('form发生了submit事件，推送码为：', formId)
    var url = "";
    formid.dealFormIds(formId, url);
    //调用接口将formid + 用户id + 过期时间 保存到数据库中TODO。。。
    if (wx.getStorageSync("userId") != "" && wx.getStorageSync("userId") != undefined) {
      that.addFormId(formId)
    }
  },

  lookmore: function() {
    var vm = this
    this.setData({
      lookmore: !vm.data.lookmore,
      classfilyDataListProgram: vm.data.alldata
    })
  },

  lookmorehistory: function() {
    var vm = this
    this.setData({
      lookmorehistory: !vm.data.lookmorehistory,
      searchhistory: vm.data.allhistorydata
    })
  },
  /**
   * 跳转到播放详情页面
   */
  todetails: function(e) {
    this.commitformid(e)
    var season = e.currentTarget.dataset.season;
    var id = e.currentTarget.dataset.id;
    var title = e.currentTarget.dataset.title; //节目标题 
    var vm = this
    //热听绑定、有声小说等、、、点击埋点 
    vm.setData({
      userIdss: wx.getStorageSync("userId"), //用户编号
      homeClassifyProgramId: id, //热听榜等。。栏目点击Id记录
      homeClassifyProgramName: title, //热听榜。。等栏目点击Name记录
    })
    wx.navigateTo({
      url: "/pages/day_day_listen/details/details?id=" + id + "&season=" + season,
      success: function() {},
      fail: function() {}
    })
  },

  //清空历史
  clearhistory: function() {
    var vm = this
    var data = {
      "userId": wx.getStorageSync("userId")
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/clearSearchHistory",
      "get", data, "清空中..",
      function(res) {
        vm.searchhistory()
      },
      function(res) {});
  },

  //记录搜索操作
  recordhistory: function(content) {
    var vm = this
    var data = {
      "userId": wx.getStorageSync("userId"),
      "content": content
    }
    getApp().request(getApp().globalData.https + "programResource/saveSearchHistory",
      "get", data,
      function(res) {
        vm.searchhistory()
      },
      function(res) {});
  },


  clear: function() {
    this.setData({
      content: '',
      before: true,
      lookmore: true,
      classfilyDataListProgram: []
    })
  },
  share: function() {},
  play: function() {
    this.setData({
      play: false
    })
  },

  change: function(event) {
    console.log("111")
    if ("" == event.detail.value) {
      this.setData({
        before: true
      })
    }
    this.setData({
      content: event.detail.value,
    })
  },
  lookallfamilysearch:function(){
    var vm=this;
    if (vm.data.openfamilysearch){
      if (vm.data.allfamilysearchhistory.length==0){
        getApp().showMsgToast("以下是全部内容");
        return
      }
      this.setData({
        familysearchhistory: vm.data.allfamilysearchhistory
      })
    }else{
      this.familysearch()
    }
    this.setData({
      openfamilysearch: !vm.data.openfamilysearch,
    })
   
  },
  familysearch: function() {
    var vm = this
    var data = {
      "userId": wx.getStorageSync("userId")
    }
    getApp().request(getApp().globalData.https + "programResource/hotSearchWord",
      "get", data,
      function(res) {
        if (res.code == 0) {
          if (res.data.length > 10) {
            vm.setData({
              familysearchhistory: res.data.slice(0, 10),
              allfamilysearchhistory: res.data,
            })
          } else {
            vm.setData({
              familysearchhistory: res.data
            })
          }
        } else {
          vm.setData({
            familysearchhistory: []
          })
        }
      },
      function(res) {});
  },

  searchhistory: function() {
    var vm = this
    var data = {
      "userId": wx.getStorageSync("userId")
    }
    getApp().request(getApp().globalData.https + "programResource/userSearchHistory",
      "get", data,
      function(res) {
        if (res.code == 0) {
          //判断历史,搜索记录个数
          if (res.data.length > 10) {
            vm.setData({
              searchhistory: res.data.slice(0, 10),
              allhistorydata: res.data,
              lookmorehistory: false
            })
          } else {
            vm.setData({
              searchhistory: res.data
            })
          }
        } else {
          vm.setData({
            searchhistory: []
          })
        }

      },
      function(res) {});
  },

  getRecomendProgram: function() {
    var vm = this
    var data = {
      "categoryId": vm.data.classfilyDataListProgram[0].categoryId,
      "userId": wx.getStorageSync("userId")
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/recommendProgram",
      "get", data, "加载中..",
      function(res) {
        if (res.code == 0) {
          vm.setData({
            recomendListProgram: res.data
          })
        }

      },
      function(res) {});
  },

  disLikeProgram: function() {
    var vm = this
    var data = {
      "programId": vm.data.recomendListProgram[dislikeindex].id,
      "userId": wx.getStorageSync("userId")
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/dislikeProgram",
      "get", data, "正在筛选..",
      function(res) {
        if (res.code == 0) {
          vm.getRecomendProgram()
        }

      },
      function(res) {});
  },

  dislike: function(event) {
    dislikeindex = event.currentTarget.dataset.index;
    this.disLikeProgram()

  },

  onenter: function(event) {
    console.log(event.detail.value)
    this.search();
  },

  searchcontent: function(e) {
    var content = e.currentTarget.dataset.content
    console.log(content)
    this.setData({
      content: content
    })
    this.search()
  },
  search: function() {
    var vm = this
    this.setData({
      classfilyDataListProgram: []
    })
    if (encodeURI(vm.data.content) == "") {
      getApp().showMsgToast("请输入搜索内容")
      return
    }
    vm.recordhistory(vm.data.content)
    var data;
    if (wx.getStorageSync("platform") != "1") {
      data = {
        "platform": 0
      }
    } else {
      data = "";
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/search?" + "condition=" + encodeURI(vm.data.content) + "&userId=" + wx.getStorageSync("userId") + "&startPoint=" + 1 + "&maxPage=" + 20,
      "get", data, "搜索中..",
      function(res) {
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          var slicedata = []
          if (res.data.length > 3) {
            slicedata = res.data.slice(0, 3)
            vm.setData({
              lookmore: false
            })
          } else {
            slicedata = res.data
            vm.setData({
              lookmore: true
            })
          }

          vm.setData({
            alldata: res.data,
            classfilyDataListProgram: slicedata,
            showbottom: false,
            before: false,
          })
          if (res.data == undefined) {
            vm.nodata(vm);
          } else {
            if (res.data.length == 0) {
              vm.nodata(vm)
            } else {
              vm.getRecomendProgram()
            }
          }
        } else {
          vm.nodata(vm)
        }
      },
      function(res) {
        console.log("222" + res)
      });
  },


  nodata: function(vm) {
    vm.setData({
      lookmore: true,
      classfilyDataListProgram: [],
      bottomtext: '没有找到你要的内容',
      showbottom: true,
      before: false
    })
    wx.showLoading({
      title: "没有找到你要的内容"
    })
    setTimeout(function() {
      wx.hideLoading()
    }, 2000)
  },


  //默认搜索词汇
  getDefaultSearchContent: function (content) {
    var vm = this
    getApp().request(getApp().globalData.https + "programResource/defaultSearchWord",
      "get", "",
      function (res) {
          if(res.code==0){
            vm.setData({
              content:res.data[0].name
            })
          }else{
            vm.setData({
              content:getApp().globalData.search_app_name
            })
          }
      },
      function (res) { });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.searchhistory()
    this.familysearch()
    this.getDefaultSearchContent()
  },
  checklogin: function() {
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
      if (wx.getStorageSync("authtype") == "0") {
        this.setData({
          showAuth: true,
          showAuth2: false
        })
      } else {
        this.setData({
          showAuth: false,
          showAuth2: true
        })
      }
      return true
    } else {
      this.setData({
        showAuth: false,
        showAuth2: false
      })
      return false
    }
  },

  /**
   * 播放音频
   */
  play: function(e) {
    if (this.checklogin()) return
    var that = this;
    let audioList = this.data.classfilyDataListProgram
    var indexNumbers = e.currentTarget.dataset.indexnumber; //当前操作对象的 index
    // 是否启用h5 
    let adl = audioList[indexNumbers]
    var id = adl.id;
    var season = e.currentTarget.dataset.season;
    var h5Url = adl.h5Url;
    if (adl.useH5 != 1) {
      //跳转页面，使用h5
      wx.navigateTo({
        url: "../../day_day_listen/details/details?id=" + id + "&season=" + season,
        success: function() {},
        fail: function() {}
      })
    } else {
      audioplayUtil.stopaudio(e, that)
      var id = e.currentTarget.dataset.id
      var programid = wx.getStorageSync("programid");
      if (id != programid) {
        that.setData({
          currentPosition: '00:00',
          duration: "00:00",
          sliderValue: 0,
        })
      }
      var indexNumberProgram = e.currentTarget.dataset.indexnumber;
      var indexNumber = e.currentTarget.dataset.season - 1;
      that.setData({
        indexNumberProgram: indexNumberProgram,
        indexNumber: indexNumber,
        pause: true, //暂停
        play: false, //播放
        classifyProgramId: id, //栏目id点击分类中的某个栏目跳转到详情播放页
        classifyProgramName: adl.title, //栏目名称
        userIdss: wx.getStorageSync("userId")
      })
      //根据栏目id查询栏目
      var data = {
        startPoint: 1,
        maxPage: 10
      }
      if (id != programid) {
        that.setData({
          page: 1
        })
      }
      audioplayUtil.getProgramCurrentSeason(id, data, that);
    }
  },

  /**
   * 监听button暂停按钮
   */
  stop: function(e) {
    console.log("暂停")
    var that = this;
    audioplayUtil.stopaudio(e, that);
    that.setData({
      pause: false, //暂停
      play: true, //播放
      indexNumberProgram: -1
    })
  },

  /**
   * 播放进度条手动调整
   */
  bindSliderchange: function(e) {
    var that = this;
    audioplayUtil.bindSliderchange(e, that)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    var id = e.target.id
    var imageUrl = getApp().globalData.shareurl
    var title = e.target.title
    if (e.from === 'button') {
      // 来自页面内转发按钮
      console.log(e.target)
      console.log("ddddddddddddddlllllllllllll---=")
    }
    var that = this;
    var userId = wx.getStorageSync("userId")
    return {
      title: wx.getStorageSync("userInfo").nickName + '邀您一起听',
      path: "/pages/style/style?userIds=" + userId + "&programIds=" + id,
      imageUrl: imageUrl,
      success(res) {
        console.log(res)
        shareTickets = res.shareTickets;
        if (shareTickets == undefined) { //执行个人分享保存
          console.log("进入个人。。。。。。。。。。。。。。")
          //分装提交数据 shareSource 栏目id  shareStatus分享状态
          var datas = {
            programId: id,
            shareSource: "0",
          }
          //暂时封印个人分享栏目保存记录TODO.....
          //that.singleGroupId(datas); //调取保存用户分享的栏目

        } else { //执行群分享保存
          console.log("进入群分享")
          var datas = {
            userId: wx.getStorageSync("userId"),
            programId: id,
            shareSource: "1",
            //shareStatus: "1"
          }
          //暂时封印组分享栏目保存记录TODO.....
          // that.getGroupID(datas); //调用获取群编号的方法
        }

      },
      fail(e) {
        console.log("fail")
      },
      //分享完成
      complete() {
        console.log("complete")
      }
    }
  },

  getGroupID: function(datas) { //获取分享群id
    wx.getShareInfo({
      shareTicket: shareTickets[0],
      success: function(res) {
        var encryptedData = res.encryptedData;
        var iv = res.iv;
        wx.login({
          success: function(res) {
            var code = res.code;
            console.log(code)
            var userId = datas.userId;
            var programId = datas.programId;
            var shareSource = datas.shareSource;
            var shareStatus = datas.shareStatus;
            var survivalTime = datas.survivalTime;
            var data = {
              'wxEncryptedData': encryptedData,
              "wxIv": iv,
              "userId": userId,
              "programId": programId,
              "shareSource": shareSource,
              //"shareStatus": shareStatus,
              //"survivalTime": survivalTime,
              "wxCode": code
            };
            console.log(data)
            //处理获取分享群信息
            app.request(app.globalData.https + "programResource/myProgramShare",
              "post", data,
              function(res) {
                console.log(res)
              },
              function(res) {
                console.log(res)
              }
            )
          }
        })
      }
    })
  },
  /**
   * 个人用户分享
   */
  singleGroupId: function(data) {
    app.request(app.globalData.https + "programResource/myProgramShare", //处理获取分享群信息
      "post", data,
      function(res) {
        if (res.code == 0) {
          console.log("调用接口" + res)
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },
})